<?php

class Cli
{
    private static $_lang = null;
    private static $_locale = null;

    /**
    * @param string Write the given string on stderror.
    */
    public static function writeOnStdError($str)
    {
        $stderr = fopen('php://stderr', 'w');
        fwrite($stderr, $str);
        fclose($stderr);
    }

    public static function setLocale($system_locale)
    {
        self::$_locale = $system_locale;
    }

    private static function prepareLang()
    {
        if (self::$_locale != null) {
            self::$_lang = getenv('LANG');
            putenv('LANG=' . self::$_locale);
        }
    }

    private static function restoreLang()
    {
        if (self::$_lang !== null) {
            putenv('LANG=' . self::$_lang);
        }
    }

    /**
    * Run a cmd and return result from stdout and stderror. Html characters are escaped.
    *
    * @param string command line
    * @param reference return value
    * @return string Ouput of STDOUT and STDERR
    */
    public static function runCmdCaptureMessage($command, &$return)
    {
        return htmlspecialchars(self::runCmdCaptureMessageUnsafe($command, $return));
    }

    /**
    * Run a cmd and return result from stdout and stderror. Unsafe doesn't escape HTML.
    *
    * @param string command line
    * @param reference return value
    * @return string Ouput of STDOUT and STDERR
    */
    public static function runCmdCaptureMessageUnsafe($command, &$return)
    {
        self::prepareLang();
        ob_start();
        passthru($command . ' 2>&1', $return);
        $msg = ob_get_contents();
        ob_end_clean();
        self::restoreLang();
        return $msg;
    }

    /**
    * Run a cmd and return result
    *
    * @param string command line
    * @return int programm return code
    */
    public static function runCmd($command)
    {
        self::prepareLang();
        ob_start();
        system($command . ' 2>&1', $return);
        ob_end_clean();
        self::restoreLang();
        return $return;
    }
}